package com.budwk.app.sqfw.services.common.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.services.common.SqfwExcelPdfForAdminCommonService;
import com.budwk.app.sqfw.vo.CheckDataForAdminVO;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.*;

/**
 * @program: dfxy-community
 * @description: 定制服务公共服务实现（后台管理系统）
 * @author: LJT
 * @create: 2024-01-23 14:02
 **/
@IocBean(name = "SqfwCustomForAdminCommonService")
@Slf4j
public class SqfwCustomForAdminCommonServiceImpl implements SqfwCustomForAdminCommonService {

    @Inject
    private SysUserService sysUserService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private CommunityStreetComponent communityStreetComponent;

    @Inject
    private SqfwExcelPdfForAdminCommonService sqfwCustomExcelForAdminCommonService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    private static final String ZHISHU = "直属";// 直属

    @Override
    public Pagination list(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        log.info("SqfwCustomForAdminCommonServiceImpl-list-SQL: {}", criteria.toString());
        Pagination pagination = sqfwFormsummaryNewService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        List<Sqfw_formSummary_new> sqfwCustomForAdminCommonVOList = pagination.getList(Sqfw_formSummary_new.class);
        if (ObjectUtil.isNotEmpty(sqfwCustomForAdminCommonVOList)) {
            List<SqfwCustomForAdminCommonVO> finalCommonVOList = new ArrayList<SqfwCustomForAdminCommonVO>();
            Map<String, String> pdfUrlMap = CommonCheckUtils.getPdfUrlByFlowId(sqfwCustomForAdminCommonVOList);
            sqfwCustomForAdminCommonVOList.forEach(source -> {
                SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
                BeanUtil.copyProperties(source, target);
                target.setPdfUrl(pdfUrlMap.get(target.getSqfwFlowId()));
                finalCommonVOList.add(target);
            });
            pagination.setList(finalCommonVOList);
        }
        log.info("SqfwCustomForAdminCommonServiceImpl-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int delete(String id) {
        int num = 0;
        Sqfw_formSummary_new sqfwFormsummaryNew = sqfwFormsummaryNewService.fetch(id);
        if (sqfwFormsummaryNew == null) {
            return num;
        }
        log.info("删除记录:{},{}", SecurityUtil.getUserId(), id);
        sqfwCompleteflowService.deleteAndUpdateWO(sqfwFormsummaryNew.getSqfwFlowId());
        return num;
    }

    @Override
    public int batchDelete(List<String> ids) {
        return 0;
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int update(Sqfw_formSummary_new sqfwFormsummaryNew) {
        sqfwFormsummaryNew.setUpdateBy(SecurityUtil.getUserId());
        sqfwFormsummaryNew.setUpdateDate(new Date());
        return sqfwFormsummaryNewService.updateIgnoreNull(sqfwFormsummaryNew);
    }

    @Override
    public List<GenerateExcelUrlVO> downloadExcel(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO sqfwCustomForAdminCommonVO) {
        return sqfwCustomExcelForAdminCommonService.generateExcel(excelConfigList, sqfwCustomForAdminCommonVO);
    }

    @Override
    public GenerateWordAndPdfUrlVO downloadPdf(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO sqfwCustomForAdminCommonVO) {
        return sqfwCustomExcelForAdminCommonService.generatePdf(excelConfigList, sqfwCustomForAdminCommonVO);
    }

    @Override
    public List<GenerateExcelUrlVO> downloadPdfList(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO sqfwCustomForAdminCommonVO) {
        return null;
    }

    @Override
    public Criteria buildQueryCond(SqfwCustomForAdminCommonVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();

        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 组装查询条件
        if (StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        }
        // 类型
        criSql.andEquals(SqfwCustomForAdminCommonVO::getType, bean.getType());

        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 省
        if (StringUtils.isNotBlank(sysUser.getProvince()) && !CommonCheckUtils.ZHISHU.equals(sysUser.getProvince())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getProvince, sysUser.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(sysUser.getCity()) && !CommonCheckUtils.ZHISHU.equals(sysUser.getCity())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCity, sysUser.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(sysUser.getDistrict()) && !CommonCheckUtils.ZHISHU.equals(sysUser.getDistrict())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getDistrict, sysUser.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(sysUser.getCounty()) && !CommonCheckUtils.ZHISHU.equals(sysUser.getCounty())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCounty, sysUser.getCounty());
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween(Sqfw_formSummary_new::getFillDate,
                    communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 辖区
        if (StringUtils.isNotBlank(bean.getCommunity())) {
            criSql.andEquals(Sqfw_formSummary_new::getCommunity, bean.getCommunity());
        }
        // 场所名称
        if (StringUtils.isNotBlank(bean.getPlaceName())) {
            criSql.andEquals("param_data->>'placeName'", bean.getPlaceName());
        }
        // 营业状态
        if (StringUtils.isNotBlank(bean.getBusinessStatus())) {
            criSql.andEquals("param_data->>'businessStatus'", bean.getBusinessStatus());
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup placeName = Cnd.exps(new Static(" param_data->>'placeName' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup businessStatus = Cnd.exps(new Static(" param_data->>'businessStatus' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup address = Cnd.exps(new Static(" param_data->>'address' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup createUserName = Cnd.exps(new Static("create_user_name like '%" + bean.getQueryAll() + "%'"));
            criSql.and(placeName.or(businessStatus).or(address).or(createUserName));
        }
        // 需要排除的数据
        criSql.andNotEquals(Sqfw_formSummary_new::getFillDate, CommonConstants.WASTE_CREATE_TIME);
        // 地址
        if (StringUtils.isNotBlank(bean.getAddress())) {
            criSql.andEquals("param_data->>'address'", bean.getAddress());
        }
        // 检查人
        if (StringUtils.isNotBlank(bean.getCreateUserName())) {
            criSql.andEquals(Sqfw_formSummary_new::getCreateUserName, bean.getCreateUserName());
        }
        // 业务需求：老版本养老只展示2024-07-18之前的数据
        criSql.and(new Static(" fill_date < '2024-07-18 00:00:00' "));
        return cri;
    }

    @Override
    public List<CheckDataForAdminVO> checkDataInfoList(SqfwCustomForAdminCommonVO bean) {
        return null;
    }

    @Override
    public void reGeneratePdf(String id) {

    }
}
